package com.wang.designpattern.interpreter;

import java.util.HashMap;
import java.util.Stack;

public class Calculator {

    // 定义表达式
    private Expression expression;

    public Calculator(String expStr) {  //  expStr = a + b
        // 运算先后顺序
        Stack<Expression> stack = new Stack<>();
        char[] charArray = expStr.toCharArray();    // [a, +, b]

        Expression left = null;
        Expression right = null;
        // 遍历字符数组，即遍历[a, +, b]
        for (int i=0; i<charArray.length; i++) {
            switch (charArray[i]) {
                case '+':
                    left = stack.pop(); // 从stack中取出a
                    right = new VarExpression(String.valueOf(charArray[++i]));  // 取出右表达式b
                    stack.push(new AddExpression(left, right)); // 构建AddExpression对象加人stack中
                    break;
                case '-':
                    left = stack.pop();
                    right = new VarExpression(String.valueOf(charArray[++i]));
                    stack.push(new SubExpression(left, right));
                    break;
                default:
                    // 如果是一个Var，就创建一个VarExpression对象，并push进stack中
                    stack.push(new VarExpression(String.valueOf(charArray[i])));
                    break;
            }
        }
        // 当遍历完整个charArray数组后，stack就得到了最后的复杂的Expression
        this.expression = stack.pop();
    }

    public int run(HashMap<String, Integer> var) {
        // 最后将表达式(a+b)和var({a=10, b=20})绑定
        // 然后传递给expression的interpreter进行解释执行
        return this.expression.interpreter(var);
    }
}
